var that;
class Tab {
    constructor(id){
        //获取元素
        this.main = document.querySelector(id);
        this.add = this.main.querySelector('.tabadd');
        //li的父元素
        this.ul = this.main.querySelector('.firstnav ul:first-child');
        //section的父元素
        this.tabscon = this.main.querySelector('.tabscon');
        this.init();
        that = this;
    }
    init(){ 
        this.updateNode();
        //init初始化操作让相关的元素绑定事件
        this.add.onclick = this.addTab;
        for( var i = 0;i<this.lis.length;i++){
            this.lis[i].index = i;
            //setAttribute('index',i)不能使用这个不然 后面调用数据拿不到
            this.lis[i].onclick = this.toggleTab;

            this.remove[i].onclick = this.removeTab;
        }
    }
    //获取所有的小li和section
    updateNode(){
        //因为我的动态添加元素，需要重新获取对应的元素
        this.lis = this.main.querySelectorAll('li');
        this.sections = this.main.querySelectorAll('section');
        this.remove = this.main.querySelectorAll('.incon-guanbi');
    }
    //1.切换功能
    toggleTab(){
        //console.log(this.index);
        that.clearClass();
        // for(var i = 0;i<this.length;i++){
        //     this.className = '';
        //     that.sections[i].className = '';
        // }
        this.className = 'liactive';
        that.sections[this.index].className = 'conactive';
    }
    clearClass(){
        for(var i = 0;i<this.lis.length;i++){
            //i<this.lis.length;在一个单独的函数里所以指向的是全局里面的数据
            this.lis[i].className = '';
            that.sections[i].className = '';
            //可以吧that 换成this
            
        }
    }
    //2.添加功能
     addTab(){
        that.clearClass();
        //创建一个随机数
        var random = Math.random();
         var li = '<li class="liactive"><span>测试1</span><span class="iconfont incon-guanbi">✖️</span></li>';
         var section = '<section class="conactive">测试'+random+'</section>';
         that.ul.insertAdjacentHTML('beforeend',li);
        //要用that 因为this指向的是点击事件add
         that.tabscon.insertAdjacentHTML('beforeend',section);
         that.init();
    }
    //3.删除功能
    removeTab(e){
        e.stopPropagation();//阻止冒泡 防止触发li 的切换点击事件
        var index = this.parentNode.index;
        // console.log(index);
        that.lis[index].remove();
        that.section[index].remove();
        that.init();
        index--;
        //手动调用我门的点击事件 不要鼠标触发
        that.lis[index] && that.lis[index].click();

    }
    //4.修改功能
    editTab(){}
}
new Tab('#tab'); 